<template>
  <div class="support-container">
    <el-card>
      <div class="header">
        <h2>维修申请管理</h2>
        <el-button type="primary" @click="handleAdd">新增申请</el-button>
      </div>

      <el-table :data="tableData" border style="width: 100%" v-loading="loading">
        <el-table-column prop="title" label="标题" />
        <el-table-column prop="description" label="详细描述" />
        <el-table-column prop="requestDate" label="申请日期" :formatter="formatDate"
                         :show-overflow-tooltip="true" />
        <el-table-column prop="userName" label="申请人" />
        <el-table-column prop="deptName" label="申请部门" />
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag :type="statusTagType(scope.row.status)">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="category" label="分类" width="120">
          <template #default="scope">
            <el-tag type="info">
              {{ scope.row.category }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="comment" label="审批意见" />
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button v-if="userRole === 'admin' || isAuthor(scope.row)"
                       size="small"
                       @click="handleEdit(scope.row)">编辑</el-button>
            <el-button
                size="small"
                type="danger"
                @click="handleDelete(scope.row.requestId)"
                :disabled="!isAuthor(scope.row) || scope.row.status !== '草稿'"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px">
      <el-form :model="form" label-width="100px">
        <el-form-item label="标题" required>
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>

        <el-form-item label="详细描述" required>
          <el-input
              v-model="form.description"
              type="textarea"
              :rows="3"
              placeholder="请输入详细问题描述"
          />
        </el-form-item>


        <el-form-item label="申请人" required>
          <el-select
              v-model="form.userId"
              placeholder="请选择申请人"
              @change="handleUserChange"
          >
            <el-option
                v-for="user in users"
                :key="user.userId"
                :label="user.userName"
                :value="user.userId"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="申请部门" required>
          <el-select v-model="form.deptId" placeholder="请选择部门" @change="handleDeptChange">
            <el-option
                v-for="dept in departments"
                :key="dept.deptId"
                :label="dept.deptName"
                :value="dept.deptId"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="状态" v-if="isEdit">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option label="草稿" value="草稿" />
            <el-option label="已提交" value="已提交" />
            <el-option label="审批通过" value="审批通过" />
            <el-option label="已驳回" value="已驳回" />
          </el-select>
        </el-form-item>

        <el-form-item label="问题分类" required>
          <el-select v-model="form.category" placeholder="请选择分类">
            <el-option
                v-for="item in categoryOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="审批意见">
          <el-input
              v-model="form.approvalComment"
              type="textarea"
              :rows="3"
              placeholder="请输入审批意见"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue';
import { computed } from 'vue'
import { useStore } from 'vuex'
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  getSupports,
  addSupport,
  updateSupport,
  deleteSupport
} from '@/api/supports';
import { getDepartments } from '@/api/departments';
import { getUsers } from '@/api/users';

export default {
  setup() {
    const loading = ref(false);
    const tableData = ref([]);
    const dialogVisible = ref(false);
    const dialogTitle = ref('新增维修申请');
    const isEdit = ref(false);

    const store = useStore();
    const userRole = computed(() => store.getters.currentUser?.role);

    // 获取当前用户ID
    const currentUserId = computed(() => store.state.user?.userId);

    // 检查是否是申请的作者
    const isAuthor = (row) => {
      return row.userId === currentUserId.value;
    };

    // 表单数据
    const form = reactive({
      requestId: null,
      title: '',
      description: '',
      requestDate: null,
      deptName: '',
      userName: '',
      status: '草稿',
      category: '',
      comment: '',
    });

    const categoryOptions = ref([
      { value: '硬件故障', label: '硬件故障' },
      { value: '软件问题', label: '软件问题' },
      { value: '网络问题', label: '网络问题' },
      { value: '办公设备', label: '办公设备' },
      { value: '其他', label: '其他' }
    ]);

    // 部门列表
    const departments = ref([]);

    // 用户列表
    const users = ref([]);

    // 状态标签类型
    const statusTagType = (status) => {
      const types = {
        '草稿': 'info',
        '已提交': '',
        '审批通过': 'success',
        '已驳回': 'danger'
      };
      return types[status] || '';
    };

    // 格式化日期显示
    const formatDate = (row, column, cellValue) => {
      if (!cellValue) return '';
      const date = new Date(cellValue);
      return date.toLocaleDateString() + ' ' + date.toLocaleTimeString();
    };

    // 用户选择变化时更新用户名
    const handleUserChange = (userId) => {
      const user = users.value.find(u => u.userId === userId);
      if (user) {
        form.userName = user.userName;
      }
    };

    // 部门选择变化时更新部门名
    const handleDeptChange = (deptId) => {
      const dept = departments.value.find(d => d.deptId === deptId);
      if (dept) {
        form.deptName = dept.deptName;
      } else {
        form.deptName = "未知部门";
      }
    };

    //获取维修表单数据
    const fetchSupports = async () => {
      loading.value = true;
      try {
        const res = await getSupports();
        console.log('原始API响应:', res); // 调试日志

        // 处理响应数据
        const dataArray = Array.isArray(res) ? res :
            (res?.data ? (Array.isArray(res.data) ? res.data : [res.data]) : []);

        tableData.value = dataArray.map(item => {
          console.log('单条数据:', item); // 调试每条数据
          return {
            requestId: item.requestId,
            title: item.title,
            description: item.description,
            requestDate: item.requestDate,
            deptName: item.deptName || '未知部门',
            userName: item.userName || item.user_name || '未知用户', // 兼容两种命名
            status: item.status,
            category: item.category,
            comment: item.comment || '' // 添加审批意见
          };
        });
      } catch (error) {
        console.error('获取数据失败:', error);
        ElMessage.error('获取维修申请失败: ' + error.message);
      } finally {
        loading.value = false;
      }
    };


    // 获取部门列表
    const fetchDepartments = async () => {
      try {
        const res = await getDepartments();
        if (!Array.isArray(res)) {
          throw new Error('API返回的数据不是数组格式');
        }
        departments.value = res;
      } catch (error) {
        ElMessage.error('获取部门列表失败: ' + error.message);
      }
    };

    //获取用户列表
    const fetchUsers = async () => {
      try {
        const res = await getUsers();
        if (!Array.isArray(res)) {
          throw new Error('API返回的数据不是数组格式');
        }
        users.value = res;
      } catch (error) {
        ElMessage.error('获取用户列表失败: ' + error.message);
      }
    };

    // 新增申请
    const handleAdd = () => {
      dialogTitle.value = '新增维修申请';
      isEdit.value = false;
      Object.assign(form, {
        requestId: null,
        title: '',
        description: '',
        requestDate: new Date(),
        userId: currentUserId.value,
        userName: '',
        deptId: departments.value[0]?.deptId || '',// 默认选择第一个部门
        deptName:departments.value[0]?.deptName || '', // 默认设置第一个部门名称
        status: '草稿',
        category: '',
        comment:'',
      });
      dialogVisible.value = true;
    };

    // 编辑申请
    const handleEdit = (row) => {
      dialogTitle.value = '编辑维修申请';
      isEdit.value = true;
      Object.assign(form, {
        requestId: row.requestId,
        title: row.title,
        description: row.description,
        requestDate: row.requestDate,
        userId: row.userId,
        userName: row.userName,
        deptId: row.deptId,
        deptName: row.deptName,
        status: row.status,
        category: row.category,
        comment:row.column || '',
      });
      dialogVisible.value = true;
    };

    // 删除申请
    const handleDelete = (id) => {
      ElMessageBox.confirm('确定删除该维修申请吗？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await deleteSupport(id);
          ElMessage.success('删除成功');
          fetchSupports();
        } catch (error) {
          ElMessage.error('删除失败: ' + error.message);
        }
      }).catch(() => {});
    };

    // 提交表单
    const handleSubmit = async () => {
      try {

        // 添加必填字段验证
        if (!form.title || !form.description) {
          ElMessage.warning('标题和描述不能为空');
          return;
        }

        if (isEdit.value) {
          await updateSupport(form);
          ElMessage.success('更新成功');
        } else {
          await addSupport(form);
          ElMessage.success('新增成功');
        }
        dialogVisible.value = false;
        fetchSupports();
      } catch (error) {
        ElMessage.error((isEdit.value ? '更新失败: ' : '新增失败: ') + error.message);
      }
    };

    onMounted(() => {
      fetchSupports();
      fetchDepartments();
      fetchUsers();
    });

    return {
      userRole,
      currentUserId,
      isAuthor,
      formatDate,
      categoryOptions,
      handleUserChange,
      handleDeptChange,

      loading,
      tableData,
      dialogVisible,
      dialogTitle,
      form,
      departments,
      users,
      isEdit,
      statusTagType,
      handleAdd,
      handleEdit,
      handleDelete,
      handleSubmit
    };
  }
};
</script>

<style scoped>
.support-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
</style>